//package com.example.recordingpen_datacollection.service.impl;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import com.example.recordingpen_datacollection.Utils.AIUtil.AIChangeUtil;
//import com.example.recordingpen_datacollection.Utils.AIUtil.ChatGlmDto;
//import com.example.recordingpen_datacollection.Utils.AIUtil.ExecuteSSEUtil;
//import com.example.recordingpen_datacollection.Utils.AIUtil.SSEListener;
//import com.example.recordingpen_datacollection.Utils.AIUtil.pojo.aliyun.AliYunJsonResult;
//import com.example.recordingpen_datacollection.Utils.DateUtils.TimeJudgeUtils;
//import com.example.recordingpen_datacollection.Utils.HtmlLayoutUtil.BDHtmlLayoutV2Util;
//import com.example.recordingpen_datacollection.Utils.SizeListUtil.LimitedSizeList;
//import com.example.recordingpen_datacollection.Utils.http.*;
//import com.example.recordingpen_datacollection.Utils.http.pojoUtil.zj.ZJJsonPutRoot;
//import com.example.recordingpen_datacollection.Utils.http.pojoUtil.zj.ZJJsonRootBean;
//import com.example.recordingpen_datacollection.Utils.hy.AIUtil;
//import com.example.recordingpen_datacollection.Utils.hy.HyResponse;
//import com.example.recordingpen_datacollection.entity.BaiduKey;
//import com.example.recordingpen_datacollection.entity.Businessdata;
//import com.example.recordingpen_datacollection.entity.DosageStatistics;
//import com.example.recordingpen_datacollection.entity.Vo.AISumUp;
//import com.example.recordingpen_datacollection.entity.Vo.AIZFYVo;
//import com.example.recordingpen_datacollection.entity.Vo.AiWatchVo;
//import com.example.recordingpen_datacollection.redisService.RedisService;
//import com.example.recordingpen_datacollection.result.exceptionhandler.BDxception;
//import com.example.recordingpen_datacollection.result.exceptionhandler.JWException;
//import com.example.recordingpen_datacollection.service.AIService;
//import com.example.recordingpen_datacollection.service.BaiduKeyService;
//import com.example.recordingpen_datacollection.service.BusinessdataService;
//import com.example.recordingpen_datacollection.service.DosageStatisticsService;
//import com.example.recordingpen_datacollection.xunfeigpt.bean.ResultBean;
//import com.example.recordingpen_datacollection.xunfeigpt.service.PushService;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.util.List;
//
//import static com.example.recordingpen_datacollection.Utils.http.HttpUrl.*;
//import static com.example.recordingpen_datacollection.config.constant.ConstantName.*;
//import static com.example.recordingpen_datacollection.config.constant.ConstantName.BD_MESSAGES_LIST;
//
//@Service
//public class AIServiceImpl_TH implements AIService {
//    @Autowired
//    private BusinessdataService businessdataService;
//    @Autowired
//    private DosageStatisticsService dosageStatisticsService;
//    @Autowired
//    private RedisService redisService;
//    @Autowired
//    private PushService pushService;
//    @Autowired
//    private BaiduKeyService baiduKeyService;
//
//    @Override
//    public String txtSumUp(AISumUp aiSumUp,Businessdata businessdataOne,boolean OnOff) {
////调用总结接口
//        String txtSumUp = "";
//        HyResponse hyresponse = null;
//        List<BaiduKey> list = null;
//
//
//
//        if(aiSumUp.getServerType() ==2){            //腾讯大模型
//            System.out.println(2);
//            String action = "ChatStd";
//            switch (aiSumUp.getAction()){
//                case 0:
//                    action= "ChatStd";
//                    break;
//                case 1:
//                    action= "ChatPro";
//                    break;
//                default:
//                    action= "ChatStd";
//                    break;
//            }
//                txtSumUp = AIUtil.staAianswer("user", aiSumUp.getContent(),action);
//            System.out.println(hyresponse  +"hyresponse");
//        }else if(aiSumUp.getServerType() ==3) {    //讯飞大模型
//            System.out.println(3);
//            ResultBean resultBean = pushService.pushMessageToXFServer(String.valueOf(aiSumUp.getLoginId()), aiSumUp.getContent());
//            txtSumUp = (String) resultBean.getData();
//        } else if(aiSumUp.getServerType() ==4  && false) {
//            System.out.println(4);
//            String access_token = null;
//
//            access_token = baiduKeyService.BDtoken();
//            if(access_token == null){
//                throw new JWException(500,"获取key失败");
//            }
//
//            try {
//                String  getBDData = BDokHttpUtil.getBDData(BDurlData,access_token, "user", aiSumUp.getContent());
//                JSONObject jsonObject = JSON.parseObject(getBDData);
//                String error_code = jsonObject.getString("error_code");
//                if(error_code != null){
//                    throw new JWException(500,getBDData);
//                }
//                // 从JSONObject中提取值
//                txtSumUp = jsonObject.getString("result");
//            } catch (IOException e) {
//                throw new JWException(500,"访问DB异常");
//            }
//        } else if(aiSumUp.getServerType() == 5 || aiSumUp.getServerType() ==4){
//            System.out.println("获取key当前请求时间-------------》"+ TimeJudgeUtils.getNowDate());
//            System.out.println(5);
//            String access_token = null;
//
//            access_token = baiduKeyService.BDtoken();
//            if(access_token == null){
//                throw new JWException(500,"获取key失败");
//            }
//
//            try {
//                String urlData = BDurl8KData;
//                if(aiSumUp.getContent().length()>5000){
//                    urlData = BDurl128KData;
//                    System.out.println("128K__");
//                }
//
//                //第一版本
//               String  getBDData = BDokHttpUtil.getBDData(urlData,access_token, "user", aiSumUp.getContent());
//                JSONObject jsonObject = JSON.parseObject(getBDData);
//                String error_code = jsonObject.getString("error_code");
//                if(error_code != null){
//                    throw new JWException(500,getBDData);
//                }
//                // 从JSONObject中提取值
//                String BDresult = jsonObject.getString("result");
//                txtSumUp = BDresult;
//
//            } catch (IOException e) {
//                throw new JWException(500,"访问DB异常");
//            }
//        } else if(aiSumUp.getServerType() == 6){   //阿里大模型
//            System.out.println(6);
//            try {
//                String aliYunJsonStr = AliYunHttpUtil.getOKHttpAliYunData("user", aiSumUp.getContent());
//                String substring = aliYunJsonStr.substring(0, 5);
//                if(substring.equals("请求错误:")){
//                    throw new JWException(400,aliYunJsonStr);
//                }
//                AliYunJsonResult aliYunJsonResult = JSON.parseObject(aliYunJsonStr, AliYunJsonResult.class);
//                txtSumUp = aliYunJsonResult.getOutput().getChoices().get(0).getMessage().getContent();
//            } catch (IOException e) {
//                throw new JWException(500,"访问aliyun异常");
//            }
//        } else if(aiSumUp.getServerType() == 7) {   //字节  火山、
//            System.out.println(7);
//            boolean zj_access_token = redisService.getKeyData(ZJ_ACCESS_TOKEN);
//            String access_token = null;
//            if(!zj_access_token){
//                String bDtokenData = null;
//                try {
//                    bDtokenData = Sign2.getApikey();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//                ZJJsonRootBean zjJsonRootBean = JSON.parseObject(bDtokenData, ZJJsonRootBean.class);
//                String apiKey = zjJsonRootBean.getResult().getApiKey();
//                access_token = apiKey;
//                long expires_in = (zjJsonRootBean.getResult().getExpiredTime()-(120*1000))/1000;    //秒
//                redisService.setTokenValue2(ZJ_ACCESS_TOKEN,expires_in,access_token);
//            } else {
//                access_token = (String)redisService.getValue(ZJ_ACCESS_TOKEN);
//                System.out.println("没有调用token");
//            }
//            try {
//                String getZJData = HuoSanHttpUtil.getZJData(HuoSanUrlData, access_token, "user", aiSumUp.getContent());
//                JSONObject jsonObject = JSON.parseObject(getZJData);
//                String error_code = jsonObject.getString("error_code");
//                if(error_code != null){
//                    throw new JWException(500,getZJData);
//                }
//                ZJJsonPutRoot zjJsonPutRoot = JSON.parseObject(getZJData, ZJJsonPutRoot.class);
//                txtSumUp = zjJsonPutRoot.getChoices().get(0).getMessage().getContent();
//            } catch (IOException e) {
//                throw new JWException(500,"访问字节 火山模型异常");
//            }
//
//        }
//
//        if(txtSumUp == null){
//            throw new JWException(500,"获取消息为null");
//        }
//        System.out.println("获取AI结果集-------------》"+ TimeJudgeUtils.getNowDate());
//        AISQLServer(aiSumUp,businessdataOne,OnOff,txtSumUp);
//
//        return new BDHtmlLayoutV2Util().convertToTXT(txtSumUp);
//    }
//
//    @Transactional
//    @Override
//    public void AISQLServer(AISumUp aiSumUp, Businessdata businessdataOne, boolean OnOff,String txtSumUp) {
//        String txt = aiSumUp.getContent();
//        //字节文本数量处理
//        if(OnOff){
//            Businessdata bus = new Businessdata();
//            bus.setId(businessdataOne.getId());
//            bus.setDosage(businessdataOne.getDosage()-txt.length());
//            boolean update = businessdataService.updateById(bus);
//            if(!update){
//                throw new JWException(500,"操作失败");
//            }
//        }
//        //存储结果集
//        DosageStatistics dosageStatistics= new DosageStatistics();
//        dosageStatistics.setLoginId(businessdataOne.getLoginId());
//        dosageStatistics.setBusinessId(aiSumUp.getServerType());
//        dosageStatistics.setTextName(aiSumUp.getTextName());
//        dosageStatistics.setUsageFrequency((long) txt.length());
//        dosageStatistics.setFinalResult(txtSumUp);
//        boolean save = dosageStatisticsService.save(dosageStatistics);
//        if(!save){
//            throw new JWException(500,"记录失败");
//        }
//    }
//
//    @Transactional
//    @Override
//    public boolean AISQLServer(AISumUp aiSumUp, Businessdata businessdataOne, boolean OnOff) {
//        String txt = aiSumUp.getContent();
//        //字节文本数量处理
//        if(OnOff){
//            Businessdata bus = new Businessdata();
//            bus.setId(businessdataOne.getId());
//            bus.setDosage(businessdataOne.getDosage()-txt.length());
//            boolean update = businessdataService.updateById(bus);
//            if(!update){
//                throw new JWException(500,"操作失败");
//            }
//        }
//        //存储结果集
//        DosageStatistics dosageStatistics= new DosageStatistics();
//        dosageStatistics.setLoginId(businessdataOne.getLoginId());
//        dosageStatistics.setBusinessId(aiSumUp.getServerType());
//        dosageStatistics.setTextName(aiSumUp.getTextName());
//        dosageStatistics.setUsageFrequency((long) txt.length());
//        dosageStatistics.setState(0);
//        dosageStatistics.setText(txt);
//        boolean save = dosageStatisticsService.save(dosageStatistics);
//        if(!save){
//            throw new JWException(500,"记录失败");
//        }
//        return save;
//    }
//
//
//
//    @Override
//    public String AITxtUp(AIZFYVo aiSumUp ) {
//        //调用总结接口
//        String txtSumUp = "";
//        String access_token = null;
//
//        access_token = baiduKeyService.payBDtoken();
//        if(access_token == null){
//            throw new JWException(500,"获取key失败");
//        }
//
//        try {
//            String  getBDData = BDokHttpUtil.getBDDataSet(access_token, "user", aiSumUp.getContent(),"Philips的AI助手");
//            JSONObject jsonObject = JSON.parseObject(getBDData);
//
//            // 从JSONObject中提取值
//             txtSumUp = jsonObject.getString("result");
//        } catch (IOException e) {
//            throw new JWException(500,"访问DB异常");
//        }
//        if(txtSumUp == null){
//            throw new JWException(500,"获取消息为null");
//        }
//
//
//        String replaceStr = new AIChangeUtil().replaceStr(txtSumUp);
//
//
//
//        return replaceStr;
//    }
//
//    @Override
//    public JSONObject txtAiWatch(AiWatchVo watchVo) {
//
//        LimitedSizeList<Messages> messageslist = null;
//        if (!redisService.getKeyData(WATCH_MESSAGES_LIST + "-" + watchVo.getDevId())) {
//            messageslist = new LimitedSizeList<>();
//            Messages messages = new Messages();
//            messages.setRole("user");
//            messages.setContent(watchVo.getContent());
//            messageslist.add(messages);
//            System.out.println(JSON.toJSONString(messageslist));
//
//        } else {
//
//            messageslist = JSON.parseObject((String) redisService.getValue(WATCH_MESSAGES_LIST + "-" + watchVo.getDevId()), LimitedSizeList.class);
//            for (Messages messages : messageslist) {
//                if(messages.getContent() == null || messages.getContent().isEmpty()){
//                    messageslist= new LimitedSizeList<>();
//                    break;
//                }
//            }
//            Messages messages = new Messages();
//            messages.setRole("user");
//            messages.setContent(watchVo.getContent());
//            messageslist.add(messages);
//        }
//
//
//        String txtSumUp = "";
//        String access_token = null;
//        System.out.println(4);
////        List<BaiduKey> list = baiduKeyService.list();
//        access_token = baiduKeyService.payBDtoken();
//        if (access_token == null) {
////            throw new JWException(500, "获取key失败");
//            throw new BDxception(101, "Failed to get key");
//        }
//
//        /**
//         * 数据记录
//         */
//
////        Aiconsult aiconsult = new Aiconsult();
////        aiconsult.setLoginId(loginId);
////        aiconsult.setProblem(aiSumUp.getContent());
////        aiconsult.setUsageFrequency((long) aiSumUp.getContent().length());
////        boolean save = this.save(aiconsult);
////        if(!save){
////            throw new JWException(500,"数据添加异常");
////        }
//        JSONObject jsonObject = null;
//        try {
//            String urlData = ERNIE_TINY_8K;
//            if (watchVo.getContent().contains("+") ||
//                    watchVo.getContent().contains("-") ||
//                    watchVo.getContent().contains("*") ||
//                    watchVo.getContent().contains("/") ||
//                    watchVo.getContent().contains("加") ||
//                    watchVo.getContent().contains("减") ||
//                    watchVo.getContent().contains("乘") ||
//                    watchVo.getContent().contains("除")) {
//                urlData = ERNIE_TINY_8K;
//
//            } else if (watchVo.getContent().contains("天气") ||
//                    watchVo.getContent().contains("气温") ||
//                    watchVo.getContent().contains("星期") ||
//                    watchVo.getContent().contains("周几") ||
//                    watchVo.getContent().contains("日期") ||
//                    watchVo.getContent().contains("几号") ||
//                    watchVo.getContent().contains("时间") ||
//                    watchVo.getContent().contains("年份")) {
//                urlData = ERNIE_TINY_8K;
//            }
//
//            String messagesJson = JSON.toJSONString(messageslist);
//            String getBDData = BDokHttpUtil.getBDData(urlData, access_token, messagesJson);
//            if (getBDData == null) {
//                throw new BDxception(16, "Access Baidu anomaly");
////                BDxceptionV2 bDxception = new BDxceptionV2(16, "Access Baidu anomaly");
////                JSONObject jsonObject2r = (JSONObject)JSONObject.toJSON(bDxception);
////                return jsonObject2r;
//            }
//            jsonObject = JSON.parseObject(getBDData);
//            System.out.println("getBDData: " + getBDData);
//            String error_code = jsonObject.getString("error_code");
//            if (error_code != null) {
//
////                redisService.setValue(BD_TOKEN_CUT, (!bd_token_cut));
////                throw new JWException(500,getBDData);
//                return jsonObject;
//            }
//            System.out.println("jsonObject: " + jsonObject);
//            // 从JSONObject中提取值
//            txtSumUp = jsonObject.getString("result");
//
//        } catch (IOException e) {
//
//            throw new BDxception(16, "Access Baidu anomaly");
//        }
//
//
//        /**
//         * 数据存储记录
//         */
////        Aiconsult aiconsult_finalResult = new Aiconsult();
////        aiconsult_finalResult.setId(aiconsult.getId());
////        aiconsult_finalResult.setFinalResult(txtSumUp);
////        boolean save_Result = this.updateById(aiconsult_finalResult);
////        if(!save_Result){
////            throw new JWException(500,"数据添加修改");
////        }
//
//
//        Messages messages = new Messages();
//        messages.setRole("assistant");
//        messages.setContent(txtSumUp);
//        messageslist.add(messages);
//        redisService.setTokenValue(WATCH_MESSAGES_LIST + "-" + watchVo.getDevId(), 2, JSON.toJSONString(messageslist));
//        System.out.println("JSON.toJSONString(messageslist) : " + JSON.toJSONString(messageslist));
//        System.out.println("messages.size() : " + messageslist.size());
//        //删除没必要的字符
////        String replaceStr = new AIChangeUtil().replaceStr(txtSumUp);
//        return jsonObject;
//    }
//
//    @Override
//    public void BDERNIE_stream(AiWatchVo watchVo, HttpServletResponse rp) {
//        String devId = watchVo.getDevId();
//
//        LimitedSizeList<Messages> messageslist = null;
//        if(!redisService.getKeyData(BD_MESSAGES_LIST+"-"+devId)){
//            messageslist = new LimitedSizeList<>();
//            Messages messages = new Messages();
//            messages.setRole("user");
//            messages.setContent(watchVo.getContent());
//            messageslist.add(messages);
//            System.out.println(JSON.toJSONString(messageslist) +" 442");
//
//        } else {
//            messageslist = JSON.parseObject((String) redisService.getValue(BD_MESSAGES_LIST+"-"+devId),LimitedSizeList.class);
//            for (Messages messages : messageslist) {
//                if(messages.getContent() == null || messages.getContent().isEmpty()){
//                    messageslist= new LimitedSizeList<>();
//                    break;
//                }
//            }
//            Messages messages = new Messages();
//            messages.setRole("user");
//            messages.setContent(watchVo.getContent());
//            messageslist.add(messages);
//        }
//
//
//
//
//        String txtSumUp = "";
//        String access_token = null;
//        access_token = baiduKeyService.payBDtoken();
//        if(access_token == null){
//            throw new BDxception(101, "Failed to get key");
//        }
//
//
//        String urlData = BDurl8KData;
//        if(watchVo.getContent().contains("+") ||
//                watchVo.getContent().contains("-") ||
//                watchVo.getContent().contains("*") ||
//                watchVo.getContent().contains("/") ||
//                watchVo.getContent().contains("加") ||
//                watchVo.getContent().contains("减") ||
//                watchVo.getContent().contains("乘") ||
//                watchVo.getContent().contains("除") ){
//            urlData = BDurl8KData;
//
//        } else if (watchVo.getContent().contains("天气") ||
//                watchVo.getContent().contains("气温") ||
//                watchVo.getContent().contains("星期") ||
//                watchVo.getContent().contains("周几") ||
//                watchVo.getContent().contains("日期") ||
//                watchVo.getContent().contains("几号") ||
//                watchVo.getContent().contains("时间") ||
//                watchVo.getContent().contains("年份")){
//            urlData = BDurl8KData;
//        }
//
////        String messagesJson = JSON.toJSONString(messageslist);
//        ChatGlmDto chatGlmDto = new ChatGlmDto();
//        chatGlmDto.setMessages(messageslist);
//        chatGlmDto.setMessageId(devId+"");
//        chatGlmDto.setSystem("小飞");
//        try {
//            String token = access_token;
//            SSEListener sseListener = new SSEListener(chatGlmDto, rp);
//            ExecuteSSEUtil.executeSSE(urlData, token, sseListener, JSON.toJSONString(chatGlmDto));
//
//
//
//            /**
//             * 获取完整数据
//             */
//            List<String> output = sseListener.getOutput();
//            if (output == null || output.size()<=0){
//                throw new BDxception(16, "Access Baidu anomaly");
//            }
//            for (String s : output) {
//                JSONObject jsonObject =  JSONObject.parseObject(s);
//                boolean resultBool = jsonObject.getBoolean("is_end");
//                if(resultBool){
//                    continue;
//                }
//                String result = jsonObject.getString("result");
//                txtSumUp+=result;
//                System.out.println(result);
//
//            }
//        } catch (Exception e) {
//            throw new BDxception(16, "Access Baidu anomaly");
//        }
//
//        Messages messages = new Messages();
//        messages.setRole("assistant");
//        messages.setContent(txtSumUp);
//        messageslist.add(messages);
//        redisService.setTokenValue(BD_MESSAGES_LIST+"-"+devId,2,JSON.toJSONString(messageslist));
//
//
//    }
//
//
//}
